import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, getRepository, Repository } from 'typeorm';
import { updataDataDto } from './dto/saveInfo.dto';
import { DailyInfo } from './saveInfo.entity';

@Injectable()
export class SaveInfoService {
  constructor(
    @InjectRepository(DailyInfo)
    private dailyInfoRepository: Repository<DailyInfo>,
  ) {}

  // 获取全部错误信息列表
  async getAllInfo() {
    const result = await getConnection()
      .createQueryBuilder()
      .select()
      .from(DailyInfo, '')
      .execute();
    return result;
  }

  // 更新表数据
  async updataTable(data: updataDataDto) {
    // 获取连接并创建新的queryRunner
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();

    // 使用我们的新queryRunner建立真正的数据库连
    await queryRunner.connect();
    // 现在我们可以在queryRunner上执行任何查询，例如：
    // const result = await queryRunner.query('SELECT * FROM sjll_pz_ll_test1');
    // 清空表
    // const result = await queryRunner.clearTable('daily_info');
    // 开始事务
    await queryRunner.startTransaction();

    // const avatarEntity = new DailyInfo();
    // avatarEntity.url = urlObj.url;

    try {
      // 清空数据表
      await queryRunner.manager
        .createQueryBuilder()
        .delete()
        .from(DailyInfo)
        .execute();

      // 插入数据表
      const result = await queryRunner.manager
        .getRepository(DailyInfo)
        .save(data);

      // user.avatar = result;

      // const userResult = await queryRunner.manager
      //   .getRepository(DailyInfo)
      //   .save(user);

      // 提交事务
      await queryRunner.commitTransaction();
      return result;
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw new ForbiddenException(error);
    }
  }
}
